#!/usr/bin/env python3  /*设定脚本文件直接能执行*/
# -*- coding:utf-8 -*-   /*设置编码*/
"""
@Author: WANDERSON M.PIMENTA
@Software: PyCharm 、Qt Designer and PySide6
@File: tQTitleBar.py
@Time: 2024/05/11 16:35
@Function：ctQTitleBar：自定义标题栏（移动、最大化、最小化、恢复、关闭按键等）
"""
from tQQtCore import *
from UI.cores.tFunctions import *
from UI.cores.tJsonSettings import Settings
from .tQTitleDivLin import ctQTitleDivLine
from .tQTitleButton import ctQTitleButton

_is_maximized = False
_old_size = QSize()


# Top bar with move application, maximize, restore, minimize,close buttons and extra buttons
class ctQTitleBar(QWidget):
    # 自定义信号
    clicked = Signal(object)
    released = Signal(object)

    # 初始化
    def __init__(self,
                 parent,
                 app_parent,
                 logo_image="logo_top_100x22.svg",
                 logo_width=100,
                 buttons=None,
                 dark_one="#1b1e23",
                 bg_color="#343b48",
                 div_color="#3c4454",
                 btn_bg_color="#343b48",
                 btn_bg_color_hover="#3c4454",
                 btn_bg_color_pressed="#2c313c",
                 icon_color="#c3ccdf",
                 icon_color_hover="#dce1ec",
                 icon_color_pressed="#edf0f5",
                 icon_color_active="#f5f6f9",
                 context_color="#6c99f4",
                 text_foreground="#8a95aa",
                 radius=8, font_family="Segoe UI",
                 title_size=10,
                 is_custom_title_bar=True,
                 ):
        super().__init__()

        # <editor-fold desc="初始化按键">
        # 标题栏最小化按键
        self.__m_btnMin = None
        # 标题栏最大化/复原按键
        self.__m_btnMax = None
        # 标题栏关闭按键
        self.__m_btnClose = None
        # 标题栏额外添加的按键
        self.__m_btnExtra = None
        # </editor-fold>

        # 调用设置文件
        settings = Settings()
        self.__m_settings = settings.items

        # <editor-fold desc="参数设置">
        # 参数设置
        self._logo_image = logo_image
        self._dark_one = dark_one
        self._bg_color = bg_color
        self._div_color = div_color
        self._parent = parent
        self._app_parent = app_parent
        self._btn_bg_color = btn_bg_color
        self._btn_bg_color_hover = btn_bg_color_hover
        self._btn_bg_color_pressed = btn_bg_color_pressed
        self._context_color = context_color
        self._icon_color = icon_color
        self._icon_color_hover = icon_color_hover
        self._icon_color_pressed = icon_color_pressed
        self._icon_color_active = icon_color_active
        self._font_family = font_family
        self._title_size = title_size
        self._text_foreground = text_foreground
        self._is_custom_title_bar = is_custom_title_bar
        # </editor-fold>

        # 调用标题栏布局函数
        self.__f_titleBarLayoutFunc()

        # 标题栏框架设置颜色
        self.__m_frame.setStyleSheet(f"background-color: {bg_color}; border-radius: {radius}px;")
        # 设置logo的最大最小宽度
        self.__m_topLogo.setMinimumWidth(logo_width)
        self.__m_topLogo.setMaximumWidth(logo_width)

        # self.__m_topLogo.setPixmap(Functions.set_svg_image(self._logo_image))

        # <editor-fold desc="标题栏移动、双击最大化&恢复">
        # 移动标题栏事件
        def __f_moveWindow(event):
            # 如果是最大化恢复正常尺寸
            if parent.isMaximized():
                self.__f_maxAndRestoreEvent()
                # self.resize(_old_size)
                curso_x = parent.pos().x()
                curso_y = event.globalPos().y() - QCursor.pos().y()
                parent.move(curso_x, curso_y)
            # 移动窗体
            if event.buttons() == Qt.LeftButton:
                parent.move(parent.pos() + event.globalPos() - parent.dragPos)
                parent.dragPos = event.globalPos()
                event.accept()

        # 标题栏各个元素增加移动事件
        if is_custom_title_bar:
            self.__m_topLogo.mouseMoveEvent = __f_moveWindow
            self.__m_divLine1.mouseMoveEvent = __f_moveWindow
            self.__m_lblTitle.mouseMoveEvent = __f_moveWindow
            self.__m_divLine2.mouseMoveEvent = __f_moveWindow
            self.__m_divLine3.mouseMoveEvent = __f_moveWindow

        # 标题栏各个元素增加双击事件（最大化&恢复）
        if is_custom_title_bar:
            self.__m_topLogo.mouseDoubleClickEvent = self.__f_maxAndRestoreEvent
            self.__m_divLine1.mouseDoubleClickEvent = self.__f_maxAndRestoreEvent
            self.__m_lblTitle.mouseDoubleClickEvent = self.__f_maxAndRestoreEvent
            self.__m_divLine2.mouseDoubleClickEvent = self.__f_maxAndRestoreEvent
        # </editor-fold>

        # <editor-fold desc="标题栏添加控件">
        # 标题栏主布局添加按键Logo、分割线、标题
        self.__m_layoutTitleBar.addWidget(self.__m_topLogo)
        self.__m_layoutTitleBar.addWidget(self.__m_divLine1)
        self.__m_layoutTitleBar.addWidget(self.__m_lblTitle)
        self.__m_layoutTitleBar.addWidget(self.__m_divLine2)

        # 标题栏主布局添加额外的按键布局
        self.__m_layoutTitleBar.addLayout(self.__m_layoutExtraBtn)

        # 标题栏主布局添加按键
        if is_custom_title_bar:
            self.__m_layoutTitleBar.addWidget(self.__m_btnMin)
            self.__m_layoutTitleBar.addWidget(self.__m_btnMax)
            self.__m_layoutTitleBar.addWidget(self.__m_btnClose)
        # </editor-fold>

        # 最小化、最大化、关闭按键的释放信号连接事件
        self.__m_btnMin.released.connect(lambda: parent.showMinimized())
        self.__m_btnMax.released.connect(lambda: self.__f_maxAndRestoreEvent())
        self.__m_btnClose.released.connect(lambda: parent.close())

    # 添加按钮(可多个)到标题栏并发送信号
    def f_titleBarAddMenus(self, parameters):
        if parameters is not None and len(parameters) > 0:
            for parameter in parameters:
                _btn_icon = Functions.f_getSvgIconPath(parameter['btn_icon'])
                _btn_id = parameter['btn_id']
                _btn_tooltip = parameter['btn_tooltip']
                _is_active = parameter['is_active']

                self.__m_btnExtra = ctQTitleButton(self._parent,
                                                   self._app_parent,
                                                   btn_id=_btn_id,
                                                   tooltip_text=_btn_tooltip,
                                                   dark_one=self._dark_one,
                                                   bg_color=self._bg_color,
                                                   bg_color_hover=self._btn_bg_color_hover,
                                                   bg_color_pressed=self._btn_bg_color_pressed,
                                                   icon_color=self._icon_color,
                                                   icon_color_hover=self._icon_color_active,
                                                   icon_color_pressed=self._icon_color_pressed,
                                                   icon_color_active=self._icon_color_active,
                                                   context_color=self._context_color,
                                                   text_foreground=self._text_foreground,
                                                   icon_path=_btn_icon,
                                                   is_active=_is_active
                                                   )

                self.__m_btnExtra.clicked.connect(self.__f_extraBtnClicked)
                self.__m_btnExtra.released.connect(self.__f_extraBtnReleased)

                # ADD TO LAYOUT
                self.__m_layoutExtraBtn.addWidget(self.__m_btnExtra)
            # 添加分割线
            if self._is_custom_title_bar:
                self.__m_layoutExtraBtn.addWidget(self.__m_divLine3)

    # 设置标题栏标题
    def f_setTitle(self, title):
        self.__m_lblTitle.setText(title)

    # <editor-fold desc="该类用到的私有方法">
    # 额外增加按键点击信号
    def __f_extraBtnClicked(self):
        self.clicked.emit(self.__m_btnExtra)

    # 额外增加按键释放信号
    def __f_extraBtnReleased(self):
        self.released.emit(self.__m_btnExtra)

    # 窗体最大化&恢复事件
    def __f_maxAndRestoreEvent(self, e=None):
        global _is_maximized
        global _old_size

        # 改变UI和调整手柄大小
        def change_ui():
            if _is_maximized:
                self._parent.ui.layoutCentralWidget.setContentsMargins(0, 0, 0, 0)
                self._parent.ui.window.f_setStylesheet(border_radius=0, border_size=0)
                self.__m_btnMax.f_setIconFunc(
                    Functions.f_getSvgIconPath("icon_restore.svg")
                )
            else:
                self._parent.ui.layoutCentralWidget.setContentsMargins(10, 10, 10, 10)
                self._parent.ui.window.f_setStylesheet(border_radius=10, border_size=2)
                self.__m_btnMax.f_setIconFunc(
                    Functions.f_getSvgIconPath("icon_maximize.svg")
                )

        # 检查事件
        if self._parent.isMaximized():
            _is_maximized = False
            self._parent.showNormal()
            change_ui()
        else:
            _is_maximized = True
            _old_size = QSize(self._parent.width(), self._parent.height())
            self._parent.showMaximized()
            change_ui()

    # 标题栏布局函数
    def __f_titleBarLayoutFunc(self):
        # 标题栏中心布局（垂直布局）
        self.__m_layoutTitleBarMiddle = QVBoxLayout(self)
        self.__m_layoutTitleBarMiddle.setContentsMargins(0, 0, 0, 0)

        # 标题栏框架
        self.__m_frame = QFrame()

        # 标题栏主布局
        self.__m_layoutTitleBar = QHBoxLayout(self.__m_frame)
        self.__m_layoutTitleBar.setContentsMargins(10, 0, 5, 0)
        self.__m_layoutTitleBar.setSpacing(0)

        # 创建分割线
        self.__m_divLine1 = ctQTitleDivLine(self._div_color)
        self.__m_divLine2 = ctQTitleDivLine(self._div_color)
        self.__m_divLine3 = ctQTitleDivLine(self._div_color)

        # 顶部Logo布局
        self.__m_topLogo = QLabel()
        self.__layoutTopLogo = QVBoxLayout(self.__m_topLogo)
        self.__layoutTopLogo.setContentsMargins(0, 0, 0, 0)
        self.__m_logoSvg = QSvgWidget()
        self.__m_logoSvg.load(Functions.f_getSvgImagePath(self._logo_image))
        self.__layoutTopLogo.addWidget(self.__m_logoSvg, Qt.AlignCenter, Qt.AlignCenter)

        # 标题Label
        self.__m_lblTitle = QLabel()
        self.__m_lblTitle.setAlignment(Qt.AlignVCenter)
        self.__m_lblTitle.setStyleSheet(f'font: {self._title_size}pt "{self._font_family}"')

        # 额外的按键布局
        self.__m_layoutExtraBtn = QHBoxLayout()
        self.__m_layoutExtraBtn.setContentsMargins(0, 0, 0, 0)
        self.__m_layoutExtraBtn.setSpacing(3)

        # <editor-fold desc="标题栏最小化按键、标题栏最大化/复原按键、标题栏关闭按键">
        # 标题栏最小化按键
        self.__m_btnMin = ctQTitleButton(self._parent,
                                         self._app_parent,
                                         tooltip_text="Close app",
                                         dark_one=self._dark_one,
                                         bg_color=self._btn_bg_color,
                                         bg_color_hover=self._btn_bg_color_hover,
                                         bg_color_pressed=self._btn_bg_color_pressed,
                                         icon_color=self._icon_color,
                                         icon_color_hover=self._icon_color_hover,
                                         icon_color_pressed=self._icon_color_pressed,
                                         icon_color_active=self._icon_color_active,
                                         context_color=self._context_color,
                                         text_foreground=self._text_foreground,
                                         radius=6,
                                         icon_path=Functions.f_getSvgIconPath("icon_minimize.svg")
                                         )

        # 标题栏最大化/复原按键
        self.__m_btnMax = ctQTitleButton(self._parent, self._app_parent,
                                         tooltip_text="Maximize app",
                                         dark_one=self._dark_one,
                                         bg_color=self._btn_bg_color,
                                         bg_color_hover=self._btn_bg_color_hover,
                                         bg_color_pressed=self._btn_bg_color_pressed,
                                         icon_color=self._icon_color,
                                         icon_color_hover=self._icon_color_hover,
                                         icon_color_pressed=self._icon_color_pressed,
                                         icon_color_active=self._icon_color_active,
                                         context_color=self._context_color,
                                         text_foreground=self._text_foreground,
                                         radius=6,
                                         icon_path=Functions.f_getSvgIconPath("icon_maximize.svg")
                                         )

        # 标题栏关闭按键
        self.__m_btnClose = ctQTitleButton(self._parent, self._app_parent,
                                           tooltip_text="Close app",
                                           dark_one=self._dark_one,
                                           bg_color=self._btn_bg_color,
                                           bg_color_hover=self._btn_bg_color_hover,
                                           bg_color_pressed=self._context_color,
                                           icon_color=self._icon_color,
                                           icon_color_hover=self._icon_color_hover,
                                           icon_color_pressed=self._icon_color_active,
                                           icon_color_active=self._icon_color_active,
                                           context_color=self._context_color,
                                           text_foreground=self._text_foreground,
                                           radius=6,
                                           icon_path=Functions.f_getSvgIconPath("icon_close.svg")
                                           )
        # </editor-fold>

        # 标题栏中心布局添加部件
        self.__m_layoutTitleBarMiddle.addWidget(self.__m_frame)
    # </editor-fold>
